import Vuex from '@/store/index.js'

export function getDeviceUUID() {
	let deviceId = uni.getStorageSync('uni_deviceId') ||
		uni.getSystemInfoSync().deviceId ||
		uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2);

	uni.setStorageSync('uni_deviceId', deviceId)
	return deviceId;
}

export const isValidSession = async () => {
  return new Promise((resolve, reject) => {
      wx.checkSession({
        success: (res) => {
          return res && res.errMsg === 'checkSession:ok' ? resolve(true) : reject(res);
        },
        fail: (err) => {
          return reject(err);
        },
      });
    })
};

export const wxLogin = async () => {
	console.log('wxLogin');
  return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          const { code } = res;
					console.log('res', res);
          if (!code) return reject(res);
          resolve(code);
        },
        fail: (err) => {
					console.error('wxLogin', err)
          return reject(err);
        },
      });
    })
};

/**
 * 微信重新登录
 */
export const wxReLogin = async (showToast = true) => {
	const code = await wxLogin()
	Vuex.commit('login', { code })
	Vuex.dispatch('loginWx', { needLogin: true, showToast })
}